package main

import (
	"fmt"
	"sync"
	"time"
)

type Result struct {
	result string
	err error
}

var (
	tasks sync.Map
	resultChan chan *Result
)


func main() {
	loop()
}

func loop() {
	nextTaskDuration := getNextTaskDuration()
	scheduleTimer := time.NewTimer(nextTaskDuration)

	//time.AfterFunc(12 * time.Second, func() {
	//	task, ok := tasks.Load("task2")
	//	if ok {
	//		task.(*Task).Status = 2
	//		task.(*Task).Cancel()
	//	}
	//})

	for {
		select {
		case res := <-resultChan:
			fmt.Println(res.result)
		case <- scheduleTimer.C:
		}

		nextTaskDuration = getNextTaskDuration()
		scheduleTimer.Reset(nextTaskDuration)
	}
}

func getNextTaskDuration() time.Duration {
	now := time.Now()
	var nextTime *time.Time

	tasks.Range(func(key, value interface{}) bool {
		task, _ := value.(*Task)

		if task.NextTime.Before(now) || task.NextTime.Equal(now) {
			task.Run()
			task.NextTime = task.Schedule.Next(now)
		}

		if nextTime == nil || task.NextTime.Before(*nextTime)  {
			nextTime = &task.NextTime
		}

		return true
	})

	return nextTime.Sub(now)
}



